package com.heima.search.message;

import cn.hutool.core.util.StrUtil;
import com.heima.common.contants.MessageConstants;
import com.heima.search.service.SearchService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SearchMessageListener {
    @Autowired
    private SearchService searchService;

    /**
     * 交换机：search.exchange
     * 队列：search.news.queue
     * key：search
     * @param message
     */
    // 监听新闻扫描队列的消息
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MessageConstants.SEARCH_QUEUE,durable = "true"),
            exchange = @Exchange(value = MessageConstants.SEARCH_EXCHANGE,type = ExchangeTypes.DIRECT),
            key = MessageConstants.SEARCH_KEY
    ))
    public void listenerSearchMessage(String message) throws Exception {
        // 如果消息为空，则直接返回
        if (StrUtil.isEmpty(message)){
            return;
        }
        // 解析消息为JSON对象
//        JSONObject jsonObject = JSONUtil.parseObj(message);
//        // "id"
//        Long id = jsonObject.getLong("id");
//        // "publishTime"
//        Date publishTime = jsonObject.getDate("publishTime");
//        // "layout"
//        Integer layout = jsonObject.getInt("layout");
//        // "images"
//        String images = jsonObject.getStr("images");
//        // "staticUrl"
//        String staticUrl = jsonObject.getStr("staticUrl");
//        // "authorId"
//        Long authorId = jsonObject.getLong("authorId");
//        // "authorName"
//        String authorName = jsonObject.getStr("authorName");
//        // "title"
//        String title = jsonObject.getStr("title");
//        // "content"
//        String content = jsonObject.getStr("content");
//        // "all"
//        String all = jsonObject.getStr("all");
//        // 创建Map
//        HashMap<String, Object> map = new HashMap<>();
//        // 封装数据
//        map.put("id",jsonObject.getLong("id"));
//        map.put("publishTime",jsonObject.getDate("publishTime"));
//        map.put("layout",jsonObject.getInt("layout"));
//        map.put("images",jsonObject.getStr("images"));
//        map.put("staticUrl",jsonObject.getStr("staticUrl"));
//        map.put("authorId",jsonObject.getLong("authorId"));
//        map.put("authorName",jsonObject.getStr("authorName"));
//        map.put("title",jsonObject.getStr("title"));
//        map.put("content",jsonObject.getStr("content"));
//        map.put("all",jsonObject.getStr("all"));
        // 调用搜索业务层，创建索引
        searchService.save(message);
    }
}
